package com.jason.bbs.comment.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.jason.bbs.bean.comment.Comment;
import com.jason.bbs.comment.dao.CommentDao;
import com.jason.bbs.comment.service.CommentService;

@Service
public class CommentServiceImpl implements CommentService {
	@Resource
	private CommentDao dao;

	@Override
	public Comment add(Comment Comment) {
		Comment.setStatus(1);
		if (Comment.getPid() == null) {
			Comment.setPid(-1);
		}
		Comment.setCreateTime(new Date());
		return dao.save(Comment);
	}

	@Override
	public void delete(String id) {
		if (exitis(id)) {
			Comment Comment = dao.findById(Integer.valueOf(id)).get();
			Comment.setStatus(0);
			dao.save(Comment);
		}
	}

	@Override
	public Page<Comment> find(Comment Comment, int pageNumber, int pageSize) {
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable page = new PageRequest(pageNumber, pageSize, sort);
		if (Comment == null) {
			return dao.findAll(page);
		} else {
			if (Comment.getStatus() == null) {
				Comment.setStatus(1);
			}
			return dao.findAll(Example.of(Comment), page);
		}
	}

	@Override
	public boolean exitis(String id) {
		Comment comment=new Comment();
		comment.setId(Integer.valueOf(id));
		comment.setStatus(1);
		return dao.exists(Example.of(comment));
	}
}
